package com.druid.conf;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * target数据源
 */
@Configuration
@MapperScan(basePackages = TargetDBConfig.PACKAGE, sqlSessionFactoryRef = "targetSqlSessionFactory")
public class TargetDBConfig {

    static final String PACKAGE = "com.druid.data.target";
    static final String MAPPER_LOCATION = "classpath:mapping/target/**.xml";

    @Value("${spring.datasource.druid.target.url}")
    public String url;

    @Value("${spring.datasource.druid.target.username}")
    private String user;

    @Value("${spring.datasource.druid.target.password}")
    private String password;

    @Value("${spring.datasource.druid.target.driver-class-name}")
    private String driverClass;

    @Value("${spring.datasource.druid.target.type}")
    private String type;

    @Bean(name = "targetDataSource")
    public DataSource targetDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setDbType(type);
        return dataSource;
    }

    @Bean(name = "targetTransactionManager")
    public DataSourceTransactionManager targetTransactionManager(@Qualifier("targetDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "targetSqlSessionFactory")
    public SqlSessionFactory targetSqlSessionFactory(@Qualifier("targetDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(TargetDBConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

}
